package com.lemon.exam.repository;

import com.lemon.exam.common.entity.view.ViewUserRoleMenuResource;
import com.lemon.exam.entity.po.UserPO;
import com.lemon.exam.entity.vo.UserVO;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * 用户表 数据访问接口
 *
 * @author Lemon
 * @since 2025/03/24 10:14:39
 */
public interface UserRepository extends R2dbcRepository<UserPO, Long> {
    @Query("SELECT id, name, username, password, status FROM sys_user WHERE username = :username AND deleted = 0 LIMIT 1")
    Mono<UserPO> findByUsername(String username);

    @Query("""
            SELECT
                role_key, menu_path, resource_path, menu_status
            FROM view_role_menu_resource
            WHERE role_status = 1
            AND role_deleted = 0
            AND role_id IN (SELECT role_id FROM sys_user_role WHERE user_id = :userId)
            """)
    Flux<ViewUserRoleMenuResource> findPathByUserId(Long userId);

    @Query("""
            SELECT
            	id,
            	username,
            	`name`,
            	phone,
            	sex,
            	email,
            	birthday,
            	avatar,
            	province_id,
            	city_id,
            	county_id,
            	address,
            	SUBSTRING_INDEX(prev_login_ip, ',', 1) AS prev_login_ip,
            	SUBSTRING_INDEX(prev_login_time, ',', 1) AS prev_login_time,
            	create_by,
            	create_time,
            	update_by,
            	update_time,
                status
            FROM
            	sys_user
            WHERE
            	id = :id
            	AND deleted = 0
            	LIMIT 1
            """)
    Mono<UserVO> findUserById(Long id);

    @Query("""
            SELECT username, name, phone, sex, email, birthday, province_id, city_id, county_id, address, create_time, status
            FROM sys_user WHERE deleted = 0 AND id IN (SELECT user_id FROM sys_user_role WHERE role_id = :roleId)
            """)
    Flux<UserVO> findUserByRoleId(Long roleId);

    @Query("""
            SELECT id, name
            FROM sys_user
            WHERE deleted = 0
            AND id IN (SELECT user_id FROM biz_class_user WHERE class_id = :classId)
            """)
    Flux<UserPO> findUserIdAndUserNameByClassId(Long classId);
}
